/**
 * created by zhouli on 2018/12/20
 * 角色（职能）菜单管理
 * todo
 * 名称做多语言
 */
import React from 'react';
import {connect} from 'react-redux';
import {Menu, Icon, Modal,Popover, Button, Form, Input, Select, Switch, Spin} from 'antd';
import 'styles/permission-setting/components/role-menu.scss';
import {deepCopy, messages, trim, getSubText} from "share/common";
import RPService from 'containers/permission-setting/role-permission-setting/role-permission-setting.service';
const FormItem = Form.Item;

//授权策略类型
let authorizationTypeList = [
  {
    name: messages('common.all')/*全部*/,
    value: "ALL",
  },
  {
    name: messages('basic-5.key13')/*人员*/,
    value: "USER",
  },
  {
    name: messages('basic-5.key14')/*人员组*/,
    value: "USER_GROUP",
  }
];

class RoleForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
    };
  }

  componentDidMount() {
  }

  //编辑form表单改变
  handleRoleChange = () => {
    this.setState({
      loading: false
    })
  };

  //渲染{messages('basic-5.key15')/*适用人员*/}
  renderSelectOption = () => {
    return authorizationTypeList.map(item => {
      return (
        item.value !== "DEPTMGR" &&
        <Option value={item.value}>{item.name}</Option>
      )
    })
  };

  handleCancel= () => {
    this.props.form.resetFields();
    this.props.onCancel && this.props.onCancel()
  }

  //保存权限
  handleSavePermission = (e) => {
    //如果没有这个，页面会刷新
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, _values) => {
      if(err)return;
      const {authorization, cRole} = this.props;
      let values = deepCopy(_values);
      values.resourcePermissionId = cRole && cRole.id || authorization.resourcePermissionId;
      if (authorization.id) {
        values.id = authorization.id;
        this.updateAuthorization(values)
      } else {
        this.createAuthorization(values)
      }
    })
  };
  //新增
  createAuthorization = (authorization) => {
    this.setState({
      loading: true
    });
    RPService.createAuthorizationItem(authorization)
      .then(res => {
        this.setState({
          loading: false,
          visible: false,
        }, () => {
          this.props.form.resetFields();
          this.props.onSave && this.props.onSave();
        })
      })
      .catch((err) => {
        this.setState({
          loading: false
        })
      })
  };
  //编辑
  updateAuthorization = (authorization) => {
    this.setState({
      loading: true
    });
    RPService.updateAuthorizationItem(authorization)
      .then(res => {
        this.setState({
          loading: false,
          visible: false,
        }, () => {
          this.props.form.resetFields();
          this.props.onSave && this.props.onSave();
        })
      })
      .catch((err) => {
        this.setState({
          loading: false
        })
      })
  };


  render() {
    const {loading} = this.state;
    const {cRole, authorization}= this.props
    const {getFieldDecorator} = this.props.form;
    return (
        <div className="role-modal-inner-wrap">
          <Form className={"new-form"}>
            <FormItem {...this.formItemLayout}
                      key={'permission-status'}
                      label={messages('common.column.status')/*状态*/}
                      colon={true}>
              {getFieldDecorator("enabled", {
                initialValue: authorization.enabled,
                valuePropName: 'checked',
              })
              (<Switch checkedChildren={<Icon type="check"/>}
                       disabled={authorization.authorizationCode === "superAdmin" }
                       unCheckedChildren={<Icon type="cross"/>}/>)
              }
              {(authorization.authorizationCode === "superAdmin") &&<div> {messages('basic-5.key16')/*超级管理员的默认授权策略不允许修改*/}
              </div>}
            </FormItem>
            <div className="sub-title">
              {messages('common.baseInfo')/*基本信息*/}
            </div>
            &nbsp;
            <FormItem {...this.formItemLayout}
              kkey={'permission-users'}
              label={messages('basic-5.key15')/*适用人员*/}
              colon={true}>
              {getFieldDecorator('authorizationType', {
                initialValue: authorization.authorizationType,
                rules: [
                  {
                    required: true,
                    message: messages('common.select')/*请选择*/
                  },
                ]
              })(
                <Select
                  placeholder={messages('common.select')/*请选择*/}
                  onChange={this.handleChange}
                >
                  {this.renderSelectOption()}
                </Select>
              )
              }
            </FormItem>
            <FormItem {...this.formItemLayout}
              key={'permission-code'}
              label={messages('basic-5.key17')/*授权编码*/}
              colon={true}>
              {getFieldDecorator('authorizationCode', {
                initialValue: authorization.authorizationCode,
                rules: [
                  {
                    required: true,
                    message: messages('common.please.input')/*请输入*/
                  },
                ]
              })(
                <Input
                  disabled={!!authorization.id}
                  placeholder={messages('common.please.input')/*请输入*/}/>)
              }
            </FormItem>
            <FormItem {...this.formItemLayout}
              key={'permission-dec'}
              label={messages('basic-5.key18')/*授权描述*/}
              colon={true}>
              {getFieldDecorator('authorizationDesc', {
                initialValue: authorization.authorizationDesc,
                rules: []
              })(
                <Input placeholder={messages('common.please.input')/*请输入*/}/>)
              }
            </FormItem>

            <div className="slide-footer">
              <Button type="primary"
                      onClick={this.handleSavePermission}
                      loading={loading}>
                {messages('common.save')/*保存*/}
              </Button>
              &nbsp;&nbsp;
              <Button onClick={this.handleCancel}>
                {messages('common.cancel')/*取消*/}
              </Button>
            </div>
          </Form>
        </div>
    )
  }
}

RoleForm.propTypes = {
  cRole: React.PropTypes.object, // 当前授权角色
  authorization: React.PropTypes.object.isRequired, // 当前授权策略
  onCancel: React.PropTypes.func.isRequired, // 取消
  onSave:  React.PropTypes.func.isRequired, // 保存
};

RoleForm.defaultProps = {

};

function mapStateToProps(state) {
  return {

  }
}

export default connect(mapStateToProps)(Form.create()(RoleForm));
